package net.sunofbeach.ucenter.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.SneakyThrows;
import net.sunofbeach.ucenter.pojo.User;
import net.sunofbeach.ucenter.mapper.UserMapper;
import net.sunofbeach.ucenter.pojo.WxCode;
import net.sunofbeach.ucenter.response.ResponseResult;
import net.sunofbeach.ucenter.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sob
 * @since 2021-12-02
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public ResponseResult listUserByPage(int page, int size) {
        //对page和size进行检查
        if(page<= 0){
            page =1;
        }
        if(size>30){
            size =30;
        }

        Page<User> queryPage = new Page<>(page-1,size);
        this.baseMapper.selectPage(queryPage,null);
        List<User> records = queryPage.getRecords();
        for (User record : records) {
            System.out.println("result item =>"+record);
        }

        return ResponseResult.SUCCESS().setData(records);
    }

    /*
    * wx鉴权校验
    * */
    @SneakyThrows
    @Override
    public ResponseResult wxAuth(WxCode wxCode) {
        System.out.println("wxCode=>"+wxCode);
        //openId 秘钥  wxCode

        String url ="https://api.weixin.qq.com/sns/jscode2session?appid=wx23c5b656980420d7&secret=b22529c7b0ece3e7f0d4b2561fc188e0&js_code="+wxCode.getCode()+"&grant_type=authorization_code";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();
        if(response.isSuccessful()){
            String body = response.body().string();
            System.out.println(body);
        }

        //入库 储存openid

        //返回token

        return ResponseResult.SUCCESS();
    }
}
